import { ChangeDetectorRef, Component, EventEmitter, OnInit, Output } from '@angular/core';
import { PropertyEntity } from '@farris/ide-property-panel';
import { MessagerService } from '@farris/ui-messager';
import { NotifyService } from '@farris/ui-notify';
import { cloneDeep } from 'lodash-es';

@Component({
  selector: 'app-field-style-config',
  templateUrl: './field-style-config.component.html',
  styleUrls: ['./field-style-config.component.css']
})
export class FieldStyleConfigComponent implements OnInit {
  @Output() valueChanged = new EventEmitter<any>();


  private _elementConfig: PropertyEntity;

  /** 列表列数据 */
  private gridFieldData: any;

  get elementConfig() {
    return this._elementConfig;
  }

  set elementConfig(value) {
    this._elementConfig = value;
    this.gridFieldData = value.editorParams.propertyData;
    this.init();
  }


  styleTypes = [
    { value: 'number', text: '数字' },
    { value: 'date', text: '日期' },
    { value: 'datetime', text: '日期时间' },
    { value: 'icon', text: '图标' },
    { value: 'none', text: '自定义' }
  ];
  styleType = 'none';

  numberPrecision = 2;
  numberFormats = [];
  standardNumberFormats = [
    { value: '{\"precision\":2,\"prefix\":\"\",\"suffix\":\"\",\"decimal\":\".\",\"thousand\":\",\"}', text: '1,234.00' },
    { value: '{\"precision\":2,\"prefix\":\"\",\"suffix\":\"元\",\"decimal\":\".\",\"thousand\":\",\"}', text: '1,234.00元' },
    { value: '{\"precision\":2,\"prefix\":\"￥\",\"suffix\":\"\",\"decimal\":\".\",\"thousand\":\",\"}', text: '￥1,234.00' },
    { value: '{\"precision\":2,\"prefix"\:\"$\",\"suffix\":\"\",\"decimal\":\".\",\"thousand\":\",\"}', text: '$1,234.00' }
  ];
  numberFormat;


  dateFormats = [];
  standardDateFormats = [
    { value: 'yyyy-MM-dd', text: '2021-11-30' },
    { value: 'yyyy年MM月dd日', text: '2021年11月30日' },
    { value: 'yyyy/MM/dd', text: '2021/11/30' },
    // { value: 'yyyyMMdd', text: '20211130' },
    { value: 'MM/dd/yyyy', text: '11/30/2021' }
  ];
  dateFormat;

  standardDatetimeFormats = [
    { value: 'yyyy-MM-dd HH:mm:ss', text: '2021-11-30 08:30:00' },
    { value: 'yyyy/MM/dd HH:mm:ss', text: '2021/11/30 08:30:00' },
    { value: 'yyyy年MM月dd日 HH时mm分ss秒', text: '2021年11月30日 08时30分00秒' },
  ];

  selectedIconType;
  iconTypes = [];
  standardIconTypes2 = [
    {
      value: 'flag',
      text: '标记',
      iconClass: [
        {
          id: 'warningFlag',
          class: 'f-icon-flag_urgent text-warning'
        }]
    },
    {
      value: 'process',
      text: '形状',
      iconClass: [
        {
          id: 'dangerRound',
          class: 'badge-round-danger'
        }, {
          id: 'infoRound',
          class: 'badge-round-info'
        },
        {
          id: 'successRound',
          class: 'badge-round-success'
        }]
    },
    {
      value: 'none',
      text: '自定义'
    }
  ];
  /** 是否显示枚举配置的确定按钮：切换为新的图标集或者需要清除原图标集时显示按钮。若之前没有配置过图标集且没有切换新图标集，则不显示按钮。 */
  showEnumIconOkBtn = true;

  /**
   * 某一系列图标包含的图标
   */
  iconClassEnums: Array<{ id: string, class: string }> = [];

  /** 枚举数据 */
  enumData: Array<{ value: string, name: string, iconClass: string }> = [];

  /** 图标id:枚举值 */
  iconEnumMapping = {};


  constructor(private msgService: MessagerService, private notifyService: NotifyService, private cd: ChangeDetectorRef) { }

  ngOnInit() {
    this.styleTypes = [];
    switch (this.gridFieldData.dataType) {
      case 'number': {
        this.styleTypes.push({ value: 'number', text: '数字' });
        this.styleType = 'number';
        break;
      }
      case 'date': case 'datetime': {
        this.styleTypes.push({ value: 'date', text: '日期' });
        this.styleType = 'date';
        break;
      }
      case 'enum': {
        this.styleTypes.push({ value: 'icon', text: '图标' });
        this.styleType = 'icon';

        break;
      }
      default: {
        this.styleTypes.push({ value: 'none', text: '自定义' });
        this.styleType = 'none';
      }
    }
  }


  init() {
    switch (this.gridFieldData.dataType) {
      case 'number': {
        this.initNumberFormat();
        break;
      }
      case 'date': {
        this.initDateFormat();
        break;
      }
      case 'datetime': {
        this.initDatetimeFormat();
        break;
      }
      case 'enum': {
        this.initEnumFormat();

        break;
      }
    }

  }

  private initNumberFormat() {
    const gridFieldFormatter = this.gridFieldData.formatter;

    this.numberPrecision = gridFieldFormatter.precision;
    this.numberFormats = cloneDeep(this.standardNumberFormats);
    this.onNumberPrecisionChanged();

    const fieldNumberFormatter = {
      precision: gridFieldFormatter.precision,
      prefix: gridFieldFormatter.prefix || '',
      suffix: gridFieldFormatter.suffix || '',
      decimal: gridFieldFormatter.decimal || '',
      thousand: gridFieldFormatter.thousand || ''
    };
    const numberFormatValue = JSON.stringify(fieldNumberFormatter);
    if (gridFieldFormatter.type !== 'number' || !this.numberFormats.find(f => f.value === numberFormatValue)) {
      this.numberFormat = null;
      this.numberFormats.push({ value: null, text: '自定义' });
    } else {
      this.numberFormat = numberFormatValue;
    }

    this.cd.detectChanges();
  }
  private initDateFormat() {
    const gridFieldFormatter = this.gridFieldData.formatter;

    const gridDateFormat = gridFieldFormatter.dateFormat;
    this.dateFormats = cloneDeep(this.standardDateFormats);


    if (gridFieldFormatter.type !== 'date' || !this.dateFormats.find(f => f.value === gridDateFormat)) {
      this.dateFormat = null;
      this.dateFormats.push({ value: null, text: '自定义' });
    } else {
      this.dateFormat = gridDateFormat;
    }
    this.cd.detectChanges();
  }

  private initDatetimeFormat() {
    const gridFieldFormatter = this.gridFieldData.formatter;

    const gridDateFormat = gridFieldFormatter.dateFormat;
    this.dateFormats = cloneDeep(this.standardDatetimeFormats);
    this.dateFormats.push(...this.standardDateFormats);


    if (gridFieldFormatter.type !== 'date' || !this.dateFormats.find(f => f.value === gridDateFormat)) {
      this.dateFormat = null;
      this.dateFormats.push({ value: null, text: '自定义' });
    } else {
      this.dateFormat = gridDateFormat;
    }
    this.cd.detectChanges();
  }

  private initEnumFormat() {
    if (this.elementConfig.editorParams.needClearConfig) {
      this.selectedIconType = null;
    }
    if (this.selectedIconType) {
      return;
    }
    this.enumData = cloneDeep(this.gridFieldData.enumData || []);
    const iconConfigForEnumData = this.gridFieldData.iconConfigForEnumData || {};

    this.iconTypes = cloneDeep(this.standardIconTypes2);
    this.selectedIconType = iconConfigForEnumData.type || '';
    if (!this.selectedIconType) {
      this.selectedIconType = 'none';
      this.showEnumIconOkBtn = false;
    } else {
      this.showEnumIconOkBtn = true;
    }
    this.iconTypes.push();
    this.iconEnumMapping = iconConfigForEnumData.iconEnumMapping || {};

    // 枚举值被删掉的场景下，要清除mapping里的数据
    const enumValues = this.enumData.map(e => e.value);
    Object.keys(this.iconEnumMapping).forEach(iconId => {
      if (!enumValues.includes(this.iconEnumMapping[iconId])) {
        this.iconEnumMapping[iconId] = null;
      }
    });
    this.changeIconClassEnums();
  }


  onNumberPrecisionChanged() {
    let decimal = '.';
    for (let i = 0; i < this.numberPrecision; i++) {
      decimal = decimal + '0';
    }
    if (decimal === '.') {
      decimal = '';
    }
    this.numberFormats.forEach(format => {
      if (format.value) {
        format.text = format.text.replace(/[.,0]/g, '').replace('4', '4' + decimal);

        let isSelected = false;
        if (this.numberFormat === format.value) {
          isSelected = true;
        }

        const value = JSON.parse(format.value);
        value.precision = this.numberPrecision;
        format.value = JSON.stringify(value);

        if (isSelected) {
          this.numberFormat = format.value;
        }
      }
    });
  }

  /**
   * 切换图标集
   */
  onIconTypeChanged() {
    this.changeIconClassEnums();
    this.iconEnumMapping = {};

    const iconConfigForEnumData = this.gridFieldData.iconConfigForEnumData || {};

    this.showEnumIconOkBtn = (iconConfigForEnumData.type || this.selectedIconType !== 'none') ? true : false;
  }

  /**
   * 变更图标的枚举数据
   */
  changeIconClassEnums() {

    const selectedIcon = this.iconTypes.find(t => t.value === this.selectedIconType);
    this.iconClassEnums = selectedIcon ? selectedIcon.iconClass : [];
  }

  sumbitStyle() {
    if (this.styleType === 'icon') {
      this.submitIconTemplateStyle();
    } else {
      this.submitFormatStyle();
    }


  }

  private submitFormatStyle() {
    this.msgService.question('应用快捷配置，将重置列格式化属性，确定应用？', () => {

      let finalValue;

      switch (this.styleType) {
        case 'number': {
          if (this.numberFormat) {
            const numberFormatValue = JSON.parse(this.numberFormat);
            const fieldNumberFormatter = {
              type: 'number',
              precision: numberFormatValue.precision,
              prefix: numberFormatValue.prefix || '',
              suffix: numberFormatValue.suffix || '',
              decimal: numberFormatValue.decimal || '',
              thousand: numberFormatValue.thousand || ''
            };
            finalValue = { formatter: fieldNumberFormatter };
          }

          this.valueChanged.emit({ elementValue: finalValue });
          break;
        }
        case 'date': {
          if (this.dateFormat) {
            finalValue = {
              formatter: {
                type: 'date',
                dateFormat: this.dateFormat
              }
            };
          }
          this.valueChanged.emit({ elementValue: finalValue });
          break;
        }
      }
    });

  }


  /**
   * 校验是否有选中的枚举值
   */
  private getSelectedIconEnum() {
    const selectedEnums = [];
    for (const iconValue of Object.keys(this.iconEnumMapping)) {
      if (this.iconEnumMapping[iconValue]) {
        selectedEnums.push(this.iconEnumMapping[iconValue]);
      }
    }
    return selectedEnums;
  }
  private submitIconTemplateStyle() {
    // 自定义图标--不影响列模板结构
    if (!this.selectedIconType) {
      this.valueChanged.emit({ elementValue: null });
      return;
    }
    if (this.selectedIconType === 'none') {
      this.clearEnumTemplate();
      return;

    }
    const selectedEnums = this.getSelectedIconEnum();
    if (selectedEnums.length === 0) {
      this.notifyService.warning('请先选择图标对应的枚举项');
      return;
    }

    const keySet = new Set(selectedEnums);
    if (Array.from(keySet).length !== selectedEnums.length) {
      this.notifyService.warning('不能重复配置枚举项，请修改');
      return;
    }

    this.msgService.question('应用图标配置，将重置列模板属性，确定应用？', () => {

      // tslint:disable-next-line:quotemark
      const originTemplate = "<span *ngIf=\"ctx.rowData.${bindingPath} === '${enumValue}'\">\r\n   ${iconClassName}${enumName}\r\n</span>";

      const { type: controlType, id: controlId, dataField } = this.gridFieldData;

      const enumTemplateArray = [];
      this.enumData.forEach(enumData => {

        // 定位图标id对应的图标class
        enumData.iconClass = '';
        for (const iconId of Object.keys(this.iconEnumMapping)) {
          if (this.iconEnumMapping[iconId] === enumData.value) {
            enumData.iconClass = this.iconClassEnums.find(c => c.id === iconId).class;
            break;
          }
        }
        let templateItem = originTemplate;

        templateItem = templateItem.replace('${bindingPath}', dataField.replace('.', '?.'));
        templateItem = templateItem.replace('${enumValue}', enumData.value);

        templateItem = templateItem.replace('${enumName}', '{{\'' + controlType + '/' + controlId + '/enumData/' + enumData.value + '\'|lang:lang:\'' + enumData.name + '\'}}');

        if (enumData.iconClass) {
          templateItem = templateItem.replace('${iconClassName}', '<span class=\"' + enumData.iconClass + ' mr-2\"></span>');
        } else {
          templateItem = templateItem.replace('${iconClassName}', '');
        }

        enumTemplateArray.push(templateItem);
      });



      const finalTemplate = enumTemplateArray.join('\r\n');

      this.valueChanged.emit({
        elementValue: {
          colTemplate: finalTemplate,
          enumIconConfig: {
            type: this.selectedIconType,
            iconEnumMapping: this.iconEnumMapping
          }
        }
      });
    });
  }
  /**
   * 枚举图标配置，切换为自定义，将清除原模板配置
   */
  private clearEnumTemplate() {
    this.msgService.question('切换自定义，将清除列模板属性，确定应用？', () => {

      this.valueChanged.emit({
        elementValue: {
          colTemplate: '',
          enumIconConfig: null
        }
      });
    });
  }
}
